package com.noahplat.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.noahplat.common.utils.Result;
import com.noahplat.common.utils.StatusCode;
import com.noahplat.user.mapper.VersionMapper;
import com.noahplat.user.pojo.User;
import com.noahplat.user.pojo.Version;
import com.noahplat.user.service.VersionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 李东
 * @version 1.0.0
 * @Date: 2021/5/8 8:43
 **/
@Service
public class VersionServiceImpl implements VersionService {

    @Autowired
    private VersionMapper versionMapper;

    /**
     * 查询版本信息
     *
     * @param stid
     * @return
     */
    @Override
    public Result getVersionByStid(Long stid) {
        Example example = new Example(Version.class);
        example.createCriteria().orEqualTo("stid", stid);
        example.setOrderByClause("id desc");
        List<Version> list = versionMapper.selectByExample(example);
        if (ObjectUtils.isEmpty(list)) {
            return new Result(true, StatusCode.ERROR, "无版本信息！");
        }
        return new Result<User>(true, StatusCode.OK, "查询成功！", list.get(0));
    }

    /**
     * 添加版本
     *
     * @param version
     * @return
     */
    @Override
    public Result addVersion(Version version) {
        Example example = new Example(Version.class);
        example.createCriteria().andEqualTo("version", version.getVersion()).andEqualTo("stid", version.getStid());
        Version version1 = versionMapper.selectOneByExample(example);
        if (!ObjectUtils.isEmpty(version1)) {
            return new Result(false, StatusCode.ERROR, "已存在该版本");
        }
        int res = versionMapper.insertSelective(version);
        if (res == 0) {
            return new Result(false, StatusCode.ERROR, "添加失败");
        }
        return new Result(true, StatusCode.OK, "添加成功");
    }

    /**
     * 分页获取版本
     *
     * @param page
     * @param limit
     * @return
     */
    @Override
    public Result getVersion(Integer page, Integer limit, String stid) {
        PageHelper.startPage(page, limit);
        List<Version> list = new ArrayList<Version>();
        if (StringUtils.isEmpty(stid)) {
            list = versionMapper.getVersion();
        } else {
            list = versionMapper.getVersionByStid(Long.parseLong(stid));
        }
        if (ObjectUtils.isEmpty(list)) {
            return new Result(false, StatusCode.NOTFOUNDERROR, "暂无数据");
        }
        PageInfo<Version> pageInfo = new PageInfo<>(list);
        return new Result(true, StatusCode.OK, "查询成功", pageInfo);
    }

}
